const axios = require('axios');

/**
 * 通过天行数据API获取食物营养信息
 * @param {string} word - 查询关键词(食品名称、分类名称或营养成分缩写)
 * @param {number} mode - 搜索模式(0:食品名称, 1:食品分类, 2:营养成分从高到低, 3:营养成分从低到高)
 * @param {number} num - 返回结果数量，默认10，最大20
 * @param {number} page - 分页参数，默认1
 * @returns {Promise} API响应数据
 */
const getNutrientInfo = async (word, mode, num = 10, page = 1) => {
  try {
    console.log(`开始请求天行API数据 - 关键词: "${word}", 模式: ${mode}, 条数: ${num}, 页码: ${page}`);
    
    // API密钥
    const apiKey = '3ba53393b6d6f0ceafd17bbfd4317605';
    
    // 构建请求URL
    const url = 'https://apis.tianapi.com/nutrient/index';
    
    console.log(`请求天行API: ${url} 参数: word=${word}, mode=${mode}, num=${num}, page=${page}`);
    
    // 发送API请求
    const response = await axios.get(url, {
      params: {
        key: apiKey,
        word,
        mode,
        num,
        page
      }
    });
    
    console.log('天行API响应状态:', response.status, response.statusText);
    console.log('天行API响应数据:', JSON.stringify(response.data));
    
    // 检查API响应状态
    if (response.data.code === 200) {
      // 正确处理result.list结构
      let resultData = null;
      
      // 检查是否有result.list格式的数据
      if (response.data.result && Array.isArray(response.data.result.list)) {
        console.log('天行API请求成功，结果列表数量:', response.data.result.list.length);
        resultData = response.data.result.list;
      }
      // 兼容处理直接返回在result中的数据
      else if (response.data.result) {
        console.log('天行API请求成功，直接使用result数据');
        resultData = Array.isArray(response.data.result) 
          ? response.data.result 
          : [response.data.result];
      }
      
      // 检查结果是否为空
      if (!resultData || resultData.length === 0) {
        console.warn(`天行API返回空结果，关键词: "${word}"`);
        return {
          success: false,
          message: '未找到相关食物信息'
        };
      }
      
      return {
        success: true,
        data: resultData
      };
    } else {
      console.warn(`天行API请求失败，错误码: ${response.data.code}, 错误信息: ${response.data.msg}`);
      return {
        success: false,
        message: response.data.msg || '获取食物营养信息失败',
        code: response.data.code
      };
    }
  } catch (error) {
    console.error('天行数据API请求失败:', error);
    // 提供更详细的错误信息
    let errorMessage = '天行数据API请求失败';
    if (error.response) {
      // 服务器返回了错误状态码
      errorMessage += `: 服务器返回 ${error.response.status} ${error.response.statusText}`;
      console.error('错误响应数据:', error.response.data);
    } else if (error.request) {
      // 请求已发送但未收到响应
      errorMessage += ': 未收到服务器响应';
    } else {
      // 请求设置时出现问题
      errorMessage += `: ${error.message}`;
    }
    
    return {
      success: false,
      message: errorMessage,
      error: error.message
    };
  }
};

/**
 * 将天行数据返回的食物营养信息转换为应用内食物模型格式
 * @param {Object} nutrientData - 天行数据API返回的食物营养信息
 * @returns {Object} 转换后的食物数据
 */
const convertToFoodModel = (nutrientData) => {
  // 记录原始数据以便调试
  console.log('天行API返回原始数据:', JSON.stringify(nutrientData));
  
  // 处理可能的空值或无效值
  const ensureNumber = (value) => {
    if (value === undefined || value === null) return 0;
    const num = parseFloat(value);
    return isNaN(num) ? 0 : num;
  };
  
  // 确保字符串值有效
  const ensureString = (value) => {
    if (value === undefined || value === null) return '';
    return String(value).trim();
  };
  
  // 根据食物类型生成常见份量
  const generateCommonPortions = (type, name) => {
    const standardPortion = { description: '一份(100g)', gramWeight: 100 };
    
    // 默认份量列表
    const portions = [standardPortion];
    
    // 根据食物类型添加特定份量
    switch (type) {
      case '谷类':
        portions.push({ description: '一小碗', gramWeight: 50 });
        portions.push({ description: '一碗', gramWeight: 150 });
        break;
      case '蔬菜类':
        portions.push({ description: '一小份', gramWeight: 50 });
        portions.push({ description: '一份', gramWeight: 150 });
        break;
      case '水果类':
        if (name.includes('苹果') || name.includes('梨') || name.includes('桃')) {
          portions.push({ description: '一个', gramWeight: 150 });
        } else if (name.includes('香蕉')) {
          portions.push({ description: '一根', gramWeight: 120 });
        } else {
          portions.push({ description: '一份', gramWeight: 120 });
        }
        break;
      case '肉类':
        portions.push({ description: '一小份', gramWeight: 50 });
        portions.push({ description: '一份', gramWeight: 100 });
        break;
      case '蛋类':
        if (name.includes('鸡蛋')) {
          portions.push({ description: '一个', gramWeight: 50 });
        }
        break;
      case '奶类':
        portions.push({ description: '一杯', gramWeight: 200 });
        break;
      case '豆类':
        portions.push({ description: '一份', gramWeight: 80 });
        break;
      default:
        portions.push({ description: '一小份', gramWeight: 50 });
    }
    
    return portions;
  };
  
  // 生成可能的食物别名
  const generateAliases = (name, type) => {
    const aliases = [];
    
    // 添加原名称
    if (name) {
      aliases.push(name);
      
      // 如果名称中有括号，提取括号前后的部分作为别名
      if (name.includes('(') || name.includes('（')) {
        const simpleName = name.replace(/[（(].*[)）]/g, '').trim();
        if (simpleName && simpleName !== name) {
          aliases.push(simpleName);
        }
      }
      
      // 添加常见简称
      if (name.length > 2) {
        const shortName = name.substring(0, 2);
        aliases.push(shortName);
      }
    }
    
    // 添加类型相关别名
    if (type && !aliases.includes(type)) {
      aliases.push(type);
    }
    
    return aliases.filter(Boolean);
  };
  
  // 检查nutrientData是否为空对象或无效
  if (!nutrientData || typeof nutrientData !== 'object') {
    console.warn('天行API返回了无效的食物数据');
    // 返回一个默认的食物对象
    return {
      name: '未知食物',
      aliases: ['未知食物'],
      category: '其他',
      calories: 0,
      carbs: 0,
      protein: 0,
      fat: 0,
      fiber: 0,
      sugar: 0,
      commonPortions: [{ description: '一份(100g)', gramWeight: 100 }],
      imageUrl: '',
      source: 'tianapi',
      isVerified: false,
      searchCount: 1
    };
  }
  
  // 转换天行API返回的数据到我们的Food模型格式
  // 直接从API返回的字段获取数据 - 使用文档提供的字段说明
  const name = ensureString(nutrientData.name || '');
  const type = ensureString(nutrientData.type || '其他');
  
  // 使用文档提供的字段映射
  // rl (float)：热量（大卡）
  // dbz (float)：蛋白质含量
  // zf (float)：脂肪含量
  // shhf (float)：碳水化合物含量
  // ssxw (float)：膳食纤维含量
  // tei (float)：铁含量 - 用作糖含量占位符
  const calories = ensureNumber(nutrientData.rl);
  const protein = ensureNumber(nutrientData.dbz);
  const fat = ensureNumber(nutrientData.zf);
  const carbs = ensureNumber(nutrientData.shhf);
  const fiber = ensureNumber(nutrientData.ssxw);
  let sugar = ensureNumber(nutrientData.tei) / 10; // 将铁含量除以10作为估计的糖含量
  
  // 额外的检查，确保有食物名称
  let displayName = name;
  if (!displayName && type) {
    displayName = `${type}食物`;
  }
  if (!displayName) {
    displayName = `食物(${Math.round(calories)}卡)`;
  }
  
  const result = {
    name: displayName,
    aliases: generateAliases(displayName, type),
    category: type,
    calories: Math.round(calories),
    carbs: parseFloat(carbs.toFixed(1)),
    protein: parseFloat(protein.toFixed(1)),
    fat: parseFloat(fat.toFixed(1)),
    fiber: parseFloat(fiber.toFixed(1)),
    sugar: parseFloat(sugar.toFixed(1)),
    commonPortions: generateCommonPortions(type, displayName),
    // 添加标准化基准量信息
    baseAmount: 100,  // 默认100克为基准量
    baseUnit: "克",   // 基准单位为克
    imageUrl: '',
    source: 'tianapi',
    isVerified: true,
    searchCount: 1
  };
  
  console.log('转换后的食物数据模型:', result);
  return result;
};

/**
 * 通过天行数据API获取菜谱信息
 * @param {string} word - 菜谱名称或食材关键词
 * @param {number} num - 返回结果数量，默认10，最大20
 * @param {number} page - 分页参数，默认1
 * @returns {Promise} API响应数据
 */
const getRecipeInfo = async (word, num = 10, page = 1) => {
  try {
    console.log(`开始请求天行菜谱API数据 - 关键词: "${word}", 条数: ${num}, 页码: ${page}`);
    
    // API密钥
    const apiKey = '3ba53393b6d6f0ceafd17bbfd4317605';
    
    // 构建请求URL
    const url = 'https://apis.tianapi.com/caipu/index';
    
    console.log(`请求天行菜谱API: ${url} 参数: word=${word}, num=${num}, page=${page}`);
    
    // 发送API请求
    const response = await axios.get(url, {
      params: {
        key: apiKey,
        word,
        num,
        page
      }
    });
    
    console.log('天行菜谱API响应状态:', response.status, response.statusText);
    
    // 检查API响应状态
    if (response.data.code === 200) {
      // 检查是否有数据
      if (response.data.result && Array.isArray(response.data.result.list) && response.data.result.list.length > 0) {
        console.log('天行菜谱API请求成功，结果列表数量:', response.data.result.list.length);
        return {
          success: true,
          data: response.data.result.list
        };
      } else {
        console.warn(`天行菜谱API返回空结果，关键词: "${word}"`);
        return {
          success: false,
          message: '未找到相关菜谱信息'
        };
      }
    } else {
      console.warn(`天行菜谱API请求失败，错误码: ${response.data.code}, 错误信息: ${response.data.msg}`);
      return {
        success: false,
        message: response.data.msg || '获取菜谱信息失败',
        code: response.data.code
      };
    }
  } catch (error) {
    console.error('天行菜谱API请求失败:', error);
    // 提供更详细的错误信息
    let errorMessage = '天行菜谱API请求失败';
    if (error.response) {
      errorMessage += `: 服务器返回 ${error.response.status} ${error.response.statusText}`;
      console.error('错误响应数据:', error.response.data);
    } else if (error.request) {
      errorMessage += ': 未收到服务器响应';
    } else {
      errorMessage += `: ${error.message}`;
    }
    
    return {
      success: false,
      message: errorMessage,
      error: error.message
    };
  }
};

/**
 * 将天行数据返回的菜谱信息转换为应用内菜谱模型格式
 * @param {Object} recipeData - 天行API返回的菜谱信息
 * @returns {Object} 转换后的菜谱数据
 */
const convertToRecipeModel = (recipeData) => {
  // 记录原始数据以便调试
  console.log('天行API返回原始菜谱数据:', JSON.stringify(recipeData));
  
  // 处理可能的空值或无效值
  const ensureString = (value) => {
    if (value === undefined || value === null) return '';
    return String(value).trim();
  };
  
  // 确保数组值有效
  const ensureArray = (value) => {
    if (!value) return [];
    if (Array.isArray(value)) return value;
    return [value];
  };
  
  // 从材料字符串中提取食材和用量
  const parseIngredients = (materials) => {
    if (!materials) return [];
    
    // 尝试解析JSON字符串
    let materialsList = materials;
    if (typeof materials === 'string') {
      try {
        materialsList = JSON.parse(materials);
      } catch (e) {
        console.warn('解析材料JSON字符串失败:', e);
        // 如果解析失败，尝试按行分割
        materialsList = materials.split(/[,，;；\n]/).filter(Boolean);
      }
    }
    
    // 确保materialsList是数组
    if (!Array.isArray(materialsList)) {
      materialsList = [materialsList];
    }
    
    // 处理材料数组
    return materialsList.map(item => {
      // 检查item是否为对象
      if (typeof item === 'object' && item !== null) {
        // 如果有name和amount属性，直接使用
        if (item.name && item.amount) {
          return {
            foodName: item.name,
            amount: item.amount,
            gramWeight: 100 // 默认值
          };
        }
      }
      
      // 如果item是字符串，尝试拆分
      const itemStr = String(item);
      const match = itemStr.match(/^(.+?)[:：]?\s*([0-9]+\.?[0-9]*\s*[克斤两片个ml毫升g份]*)$/);
      
      if (match) {
        const name = match[1].trim();
        const amount = match[2].trim();
        // 简单估算克重
        let gramWeight = 100; // 默认值
        
        if (amount.includes('克') || amount.includes('g')) {
          gramWeight = parseInt(amount);
        } else if (amount.includes('斤')) {
          gramWeight = parseInt(amount) * 500;
        } else if (amount.includes('两')) {
          gramWeight = parseInt(amount) * 50;
        } else if (amount.includes('毫升') || amount.includes('ml')) {
          gramWeight = parseInt(amount);
        }
        
        return {
          foodName: name,
          amount: amount,
          gramWeight: gramWeight || 100
        };
      } else {
        // 无法解析的情况
        return {
          foodName: itemStr,
          amount: '适量',
          gramWeight: 50
        };
      }
    });
  };
  
  // 从步骤字符串中提取步骤
  const parseSteps = (process) => {
    if (!process) return [];
    
    // 尝试解析JSON字符串
    let stepsList = process;
    if (typeof process === 'string') {
      try {
        stepsList = JSON.parse(process);
      } catch (e) {
        console.warn('解析步骤JSON字符串失败:', e);
        // 如果解析失败，尝试按行分割
        stepsList = process.split(/\n/).filter(Boolean);
      }
    }
    
    // 确保stepsList是数组
    if (!Array.isArray(stepsList)) {
      stepsList = [stepsList];
    }
    
    // 处理步骤数组
    return stepsList.map((step, index) => {
      if (typeof step === 'object' && step !== null) {
        return {
          order: index + 1,
          description: step.step || step.description || `步骤${index + 1}`,
          imageUrl: step.image || step.imageUrl || ''
        };
      } else {
        return {
          order: index + 1,
          description: String(step),
          imageUrl: ''
        };
      }
    });
  };
  
  // 估算营养成分
  const estimateNutrition = (foodType, ingredients) => {
    const defaults = {
      'vegetable': { calories: 300, carbs: 30, protein: 15, fat: 10 },
      'meat': { calories: 450, carbs: 15, protein: 40, fat: 25 },
      'seafood': { calories: 350, carbs: 10, protein: 35, fat: 15 },
      'dessert': { calories: 400, carbs: 60, protein: 10, fat: 15 },
      'soup': { calories: 250, carbs: 25, protein: 15, fat: 10 },
      'staple': { calories: 500, carbs: 80, protein: 15, fat: 10 },
      'default': { calories: 380, carbs: 40, protein: 20, fat: 15 }
    };
    
    // 根据食材数量微调
    const count = ingredients.length;
    let multiplier = 1;
    
    if (count >= 10) multiplier = 1.3;
    else if (count >= 6) multiplier = 1.1;
    else if (count <= 3) multiplier = 0.8;
    
    // 获取默认值
    let nutrition = defaults[foodType] || defaults.default;
    
    // 应用乘数
    return {
      calories: Math.round(nutrition.calories * multiplier),
      carbs: Math.round(nutrition.carbs * multiplier),
      protein: Math.round(nutrition.protein * multiplier),
      fat: Math.round(nutrition.fat * multiplier)
    };
  };
  
  // 提取主要信息
  const name = ensureString(recipeData.cpName || recipeData.name || recipeData.title || '未命名菜谱');
  const description = ensureString(recipeData.tip || recipeData.description || '');
  const ingredients = parseIngredients(recipeData.material || recipeData.ingredients || recipeData.materials);
  const steps = parseSteps(recipeData.process || recipeData.steps || recipeData.instructions);
  const imageUrl = ensureString(recipeData.pic || recipeData.food_pic || recipeData.imageUrl || '');
  const tags = ensureArray(recipeData.tag || recipeData.tags);
  const type = ensureString(recipeData.type || recipeData.foodType || '其他');
  
  // 根据食材和类型估算营养成分
  const nutrition = estimateNutrition(type, ingredients);
  
  // 确定菜谱分类
  const getCategory = (typeName, ingredientsList) => {
    // 根据类型确定主分类
    const typeLower = typeName.toLowerCase();
    let categories = [];
    
    if (typeLower.includes('汤') || typeLower.includes('羹')) categories.push('soup');
    else if (typeLower.includes('甜品') || typeLower.includes('点心')) categories.push('snack');
    else if (typeLower.includes('饭') || typeLower.includes('面')) categories.push('grain');
    
    // 根据食材确定子分类
    const ingredientNames = ingredientsList.map(ing => ing.foodName.toLowerCase());
    const containsIngredient = (keywords) => keywords.some(keyword => 
      ingredientNames.some(name => name.includes(keyword))
    );
    
    if (containsIngredient(['鸡', '鸭', '鸟'])) categories.push('chicken');
    if (containsIngredient(['猪', '肉', '排骨', '肘子'])) categories.push('pork');
    if (containsIngredient(['牛', '羊'])) categories.push('beef');
    if (containsIngredient(['鱼', '虾', '蟹', '贝', '海'])) categories.push('seafood');
    if (containsIngredient(['豆', '腐'])) categories.push('bean');
    if (containsIngredient(['菜', '芹', '瓜', '萝卜', '番茄', '土豆', '洋葱'])) categories.push('vegetable');
    if (containsIngredient(['米', '麦', '面', '粉', '饭', '面条'])) categories.push('grain');
    if (containsIngredient(['果', '苹', '香蕉', '梨'])) categories.push('fruit');
    
    // 至少有一个分类
    if (categories.length === 0) categories.push('all');
    
    return [...new Set(categories)];
  };
  
  // 确定适合的膳食类型
  const getMealType = (name, typeName) => {
    const nameLower = name.toLowerCase();
    const typeLower = typeName.toLowerCase();
    const mealTypes = [];
    
    if (nameLower.includes('早餐') || nameLower.includes('早饭') || 
        typeLower.includes('早餐') || typeLower.includes('早饭')) {
      mealTypes.push('breakfast');
    }
    
    if (nameLower.includes('午餐') || nameLower.includes('午饭') || 
        typeLower.includes('午餐') || typeLower.includes('午饭')) {
      mealTypes.push('lunch');
    }
    
    if (nameLower.includes('晚餐') || nameLower.includes('晚饭') || 
        typeLower.includes('晚餐') || typeLower.includes('晚饭')) {
      mealTypes.push('dinner');
    }
    
    if (nameLower.includes('点心') || nameLower.includes('零食') || 
        typeLower.includes('点心') || typeLower.includes('零食') ||
        typeLower.includes('甜品')) {
      mealTypes.push('snack');
    }
    
    // 如果没有明确指定，根据类型和食材推断
    if (mealTypes.length === 0) {
      if (typeLower.includes('汤') || typeLower.includes('主食')) {
        mealTypes.push('lunch', 'dinner');
      } else if (typeLower.includes('小吃') || typeLower.includes('甜点')) {
        mealTypes.push('snack');
      } else {
        // 默认为午餐和晚餐
        mealTypes.push('lunch', 'dinner');
      }
    }
    
    return [...new Set(mealTypes)];
  };
  
  // 构建最终模型
  const result = {
    name,
    description,
    // 营养信息
    calories: nutrition.calories,
    carbs: nutrition.carbs,
    protein: nutrition.protein,
    fat: nutrition.fat,
    fiber: Math.round(nutrition.carbs * 0.15), // 估算值
    sugar: Math.round(nutrition.carbs * 0.3),  // 估算值
    
    isNutritionCalculated: false, // 标记为估算值
    servingSize: 1,
    cookingTime: Math.max(10, Math.min(90, steps.length * 5)), // 根据步骤数估算
    difficulty: steps.length > 8 ? '困难' : (steps.length > 4 ? '中等' : '简单'),
    imageUrl,
    
    // 分类信息
    mealType: getMealType(name, type),
    category: getCategory(type, ingredients),
    
    // 详细信息
    ingredients,
    steps,
    tags: [...tags, type], // 将类型也添加为标签
    
    // 适合的健康状况 - 根据营养成分评估
    suitableFor: [],
    featured: false,
    source: 'tianapi',
    originalData: recipeData // 保存原始数据
  };
  
  // 评估适合度
  if (nutrition.carbs < 30) {
    result.suitableFor.push({ condition: '糖尿病', stage: '全阶段' });
    result.tags.push('低碳水');
  } else if (nutrition.carbs < 50) {
    result.suitableFor.push({ condition: '糖尿病', stage: '轻度' });
    result.tags.push('中碳水');
  }
  
  if (nutrition.fat < 15) {
    result.suitableFor.push({ condition: '高血脂', stage: '全阶段' });
    result.tags.push('低脂');
  }
  
  if (nutrition.protein > 25) {
    result.tags.push('高蛋白');
  }
  
  console.log('转换后的菜谱数据模型:', result);
  return result;
};

/**
 * 获取优化的营养素数据
 * @param {string} keyword - 搜索关键词
 * @param {number} mode - 搜索模式：0营养成分、1食品分类、2营养正序、3营养倒序
 * @param {string} nutritionType - 指定的营养素类型(可选)
 * @param {number} num - 返回数量，默认10
 * @param {number} page - 页码，默认1
 * @returns {Promise<Array>} - 返回匹配的食物数据
 */
exports.getOptimizedNutrientInfo = async (keyword, mode, nutritionType = null, num = 10, page = 1) => {
  try {
    console.log(`获取优化营养素数据: keyword=${keyword}, mode=${mode}, nutritionType=${nutritionType}, num=${num}, page=${page}`);
    
    // 调用基础API获取数据
    const response = await exports.getNutrientInfo(keyword, mode, num, page);
    
    if (!response.success) {
      console.error('天行API调用失败:', response.message);
      return [];
    }
    
    let results = [];
    
    // 处理API返回的数据
    if (Array.isArray(response.data)) {
      results = response.data;
    } else if (response.data && typeof response.data === 'object') {
      results = [response.data];
    }
    
    // 如果指定了营养素类型且是排序模式，添加营养素过滤
    if (nutritionType && (mode === 2 || mode === 3)) {
      console.log(`按营养素 ${nutritionType} 过滤结果`);
      
      results = results.filter(item => {
        if (!item.nutrition || typeof item.nutrition !== 'object') {
          return false;
        }
        
        // 确保营养素值存在且大于0
        const nutritionValue = parseFloat(item.nutrition[nutritionType]);
        return !isNaN(nutritionValue) && nutritionValue > 0;
      });
    }
    
    // 按营养素含量进行分类标记
    results = results.map(item => {
      if (!item.nutrition) return item;
      
      const nutrition = item.nutrition;
      let tags = [];
      
      // 高蛋白质食物
      if (parseFloat(nutrition.protein) > 15) {
        tags.push('高蛋白');
      }
      
      // 高纤维食物
      if (parseFloat(nutrition.fiber) > 5) {
        tags.push('高纤维');
      }
      
      // 低脂肪食物
      if (parseFloat(nutrition.fat) < 3) {
        tags.push('低脂肪');
      }
      
      // 低碳水食物
      if (parseFloat(nutrition.carbohydrate) < 10) {
        tags.push('低碳水');
      }
      
      // 计算营养密度(蛋白质/卡路里比率)
      const calories = parseFloat(nutrition.calories) || 1; // 避免除以0
      const protein = parseFloat(nutrition.protein) || 0;
      
      if (protein / calories > 0.1) { // 10%以上的卡路里来自蛋白质
        tags.push('高营养密度');
      }
      
      return {
        ...item,
        tags
      };
    });
    
    console.log(`优化后的结果数量: ${results.length}`);
    return results;
  } catch (error) {
    console.error('获取优化营养素数据失败:', error);
    return [];
  }
};

module.exports = {
  getNutrientInfo,
  convertToFoodModel,
  getRecipeInfo,
  convertToRecipeModel,
  getOptimizedNutrientInfo: exports.getOptimizedNutrientInfo
}; 